/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.hlwjr.downloader.work;

//import cn.ac.iie.di.ban.hlwjr.downloader.global.GlobalParas;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.logging.Level;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

/**
 *
 * @author wanglin
 */
public class UnTarFilePath implements Runnable {

    public static Logger log = Logger.getLogger(UnTarFilePath.class.getName());
    SimpleDateFormat simp = new SimpleDateFormat("yyyyMMddHH");
    private ArrayBlockingQueue<String> filePool=null;
    private boolean isQuit=false;
    private String dataType="";
    String filePath;

    public UnTarFilePath(String filePath,ArrayBlockingQueue<String> filePool,String dataType) {
        this.filePath = filePath;
        this.filePool=filePool;
        this.dataType=dataType;
    }

    public static void main(String[] args) {
        File file = new File("E:\\test\\sfiles\\a.tar");
        try {
            FileUtils.moveFileToDirectory(file, new File("E:\\test\\tempFile"), true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        System.out.println("1");
    }

    @Override
    public void run() {
        File fileDir = new File(filePath);
        if (fileDir.isDirectory()) {
            while (true) {
                int i = 0;
                File[] files = fileDir.listFiles();
                List<String> okFile = new ArrayList<String>();
                for (File file : files) {
//                    String tmpPath = GlobalParas.catchFilePath + File.separator +simp.format(System.currentTimeMillis()) + System.nanoTime();
                    
                    String tmpPath = "E:\\test\\sfiles" + File.separator +simp.format(System.currentTimeMillis()) + System.nanoTime();
                    if (file.getName().contains("tar")) {
                        try {
                            untar(file, tmpPath);
                            okFile.add(file.getAbsolutePath());
                        } catch (Exception ex) {
                            log.debug("untar or put path to pool failed for" + ex.getMessage(), ex);
                            try {
                                FileUtils.deleteDirectory(new File(tmpPath));
                            } catch (Exception ex1) {
                                ex.printStackTrace();
                            }
                            continue;
                        }
                        try {
                            this.filePool.put(tmpPath);
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                    }
                }
                for (String okPath : okFile) {
                    try {
//                        FileUtils.moveFileToDirectory(new File(okPath), new File(GlobalParas.successFilePath +"/"+dataType+ File.separator + simp.format(System.currentTimeMillis()) + File.separator), true);
                        
                         FileUtils.moveFileToDirectory(new File(okPath), new File("E:\\test\\parserFiles" +"/"+dataType+ File.separator + simp.format(System.currentTimeMillis()) + File.separator), true);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        log.warn("move file to successPath failed for " + ex.getMessage(), ex);
                    }

                }
                log.info("get " + i + " file from the dir, will sleep...");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException ex) {
                }
                if (isQuit) {
                    break;
                }
            }
        }
    }

    public static void untar(File tarFile, String purposePath) throws Exception {
//            String tarPath = "H:\\test.tar";
        TarArchiveInputStream taos = new TarArchiveInputStream(new FileInputStream(tarFile));
        ArchiveEntry archiveEntry = null;
        while ((archiveEntry = taos.getNextEntry()) != null) {
            String entryFileName = archiveEntry.getName();
            String entryFilePath = purposePath + File.separator + entryFileName;
            OutputStream os = null;
            try {
                // 把解压出来的文件写到指定路径
                File entryFile = new File(entryFilePath);
                if (!entryFile.getParentFile().exists()) {
                    entryFile.getParentFile().mkdirs();
                    
                    entryFile.createNewFile();
                }
                if (entryFileName.endsWith("/")) {
                    entryFile.mkdirs();
                } else {
                    os = new BufferedOutputStream(new FileOutputStream(entryFile));
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    while ((len = taos.read(buffer)) != -1) {
                        os.write(buffer, 0, len);
                    }
                }
            } catch (Exception e) {

                throw new Exception(e);
            } finally {
                if (os != null) {
                    os.flush();
                    os.close();
                }
            }
        }
        taos.close();
    }

    public void setIsQuit(boolean isQuit) {
        this.isQuit = isQuit;
    }

}
